﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WarOfDev.EF;
using WarOfDev.Web.Models.MappingToViewModel;
using WarOfDev.Web.ViewModels;
using WarOfDev.Web.ViewModels.MappingToModel;

namespace WarOfDev.Web.Controllers
{
    public class RoleController : Controller
    {
        private WarDevEntities db = new WarDevEntities();

        //
        // GET: /Role/

        public ActionResult Index()
        {
            return View(db.Roles.Include("Groups").Include("Groups.Group").AsEnumerable().Select(r=>r.ToViewModel()).ToList());
        }

        //
        // GET: /Role/Details/5

        public ActionResult Details(string id = null)
        {
            Role role = db.Roles.Single(r => r.Id == id);
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role);
        }

        //
        // GET: /Role/Create

        public ActionResult Create()
        {
            ViewBag.GroupId = new SelectList(db.Groups, "Id", "GroupName");
            return View();
        }

        //
        // POST: /Role/Create

        [HttpPost]
        public ActionResult Create(RoleViewModel role, string[] permissionValues)
        {
            if (ModelState.IsValid)
            {
                role.Id = Guid.NewGuid().ToString();
                role.CreatedOn = DateTime.Now;
                role.ModifiedOn = DateTime.Now;
                role.Permissions = Request["permissionValues"].ToString();

                db.Roles.AddObject(role.ToModel());

                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(role);
        }

        //
        // GET: /Role/Edit/5

        public ActionResult Edit(string id)
        {
            Role role = db.Roles.Include("Groups").Single(r => r.Id == id);
            ViewBag.GroupId = new SelectList(db.Groups.Select(g => new SelectListItem { Text = g.GroupName, Value = g.Id, Selected = role.Groups.Count() > 0 ? g.Id == role.Groups.First().GroupId : false }), "Id", "GroupName");
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role.ToViewModel());
        }

        //
        // POST: /Role/Edit/5

        [HttpPost]
        public ActionResult Edit(RoleViewModel role)
        {
            if (ModelState.IsValid)
            {
                role.Groups = db.GroupRoles.Where(gr => gr.GroupId == role.GroupId && gr.RoleId == role.Id).ToList();
                role.Permissions = Request["permissionValues"].ToString();
                var model = role.ToModel();

                db.Roles.Attach(model);

                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);

                //var addGroups = role.Groups.Except(model.Groups).ToList();
                //var deleteGroups =model.Groups.Except(role.Groups).ToList();
                //var modifyGroups = role.Groups.Intersect(model.Groups).ToList();

                //addGroups.ForEach(g =>db.GroupRoles.AddObject(g));
                //deleteGroups.ForEach(g => db.GroupRoles.DeleteObject(g));
                //modifyGroups.ForEach(g => db.GroupRoles.ApplyCurrentValues(g));

                foreach (var item in model.Groups)
                {
                    db.GroupRoles.Attach(item);
                    if (db.GroupRoles.FirstOrDefault(g => g.RoleId == role.Id && g.GroupId == item.GroupId) != null)
                    {
                        db.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
                    }
                    else
                    {
                        db.ObjectStateManager.ChangeObjectState(item, EntityState.Added);
                    }
                }

                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(role);
        }

        //
        // GET: /Role/Delete/5

        public ActionResult Delete(string id = null)
        {
            Role role = db.Roles.Single(r => r.Id == id);
            if (role == null)
            {
                return HttpNotFound();
            }
            return View(role);
        }

        //
        // POST: /Role/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            Role role = db.Roles.Single(r => r.Id == id);
            db.Roles.DeleteObject(role);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult GetAllPermissions(string selectedPermissions)
        {
            var permissions = db.Permissions.AsEnumerable().Select(p => p.ToViewModel(selectedPermissions));
            return PartialView("_AllPermissions", permissions);
        }

        public ActionResult GetAllGroups(string id)
        {
            var groups = new List<SelectListItem> { new SelectListItem { Value = string.Empty, Text = "Select Department" } };
            groups.AddRange(db.Groups.AsEnumerable().Select(g => new SelectListItem { Text = g.GroupName, Value = g.Id, Selected = g.Id == id }));

            return PartialView("_AllGroups", groups);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}